<template>
  <base-modal
    :title="title"
    width="676px"
    :show.sync="isShow"
    :mask-closeable="false">
    <div class="add-form task-form">
        <el-tag type="warning"><i class="el-icon-warning"></i> {{ $t('projectManage.setting.taskSetting.tip1') }}</el-tag>
        <div class="task-rule-wrap">
          <ConnectorModuleRuleForm
          v-if="showForm"
          :toFieldList="toFieldList"
          :fromFieldList="fromFieldList"
          :value="insertFieldOptionsList"
          :fromBizTypeName="$t('projectManage.setting.projectName')"
          :toBizTypeName="selectTypeName"
          :isShowOperate="false"
          @input="onConnectorSelectRuleFormInputHandler"
          />
        </div>
         <el-button type="primary" plain @click="addRuleFormItem"> + {{ $t('common.connector.buttons.addField') }}</el-button>
    </div>
    <div slot="footer">
      <el-button @click="cancel">{{$t('common.base.cancel')}}</el-button>
      <el-button :loading="pedding" type="primary" @click="submitForm">{{$t('common.base.save')}}</el-button>
    </div>
  </base-modal>
</template>
<script>

import _ from 'lodash';
import { ConnectorModuleRuleForm } from '@src/modules/connector/components'

import { connectorFromFieldsAddChildren } from '@src/modules/connector/util';
import { createConnectorRuleFormItem } from '@src/modules/connector/util'
import * as ProjectManage from '@src/api/ProjectManage.ts';
import { getConnectorOptions } from '@src/modules/connector/api'
import {connectorRuleFormToConnectorOptionsFieldOption, ConnectorOptionsFieldOptionToConnectorRuleForm} from '@src/modules/connector/util/card';

export default {
  name: 'create-rule',
  data() {
    return {
      title: this.$t('common.base.createRuler'),
      form: {
        projectTaskName: '',
        projectTaskDesc: '',
        taskType: '',
        taskFormId: '',
        preTaskId: [],
      },
      rules: {
        projectTaskName: [
          { required: true, message: this.$t('projectManage.setting.taskSetting.placeholder2'), trigger: 'blur' },
          { max: 20, message: this.$t('projectManage.setting.taskSetting.ruleMess1'), trigger: 'blur' }
        ],
        taskFormId: [
          {required: true, message: this.$t('projectManage.setting.taskSetting.placeholder3'), trigger: 'change' }
        ],
        projectTaskDesc: [
          { required: true, message: this.$t('projectManage.setting.taskSetting.placeholder5'), trigger: 'blur' },
        ]
      },
      taskProps: {
        multiple: false,
        value: 'id',
        label: 'name',
        emitPath: false,
        children: 'formList',
      },
      pedding: false,
      isShow: false,
      insertFieldOptionsList:[],
      fromFieldList:[],
      toFieldList:[],
      selectTypeName: '', // 选中的任务类型名称
      preTaskList: [],// 前置任务
      taskId: null, // 任务的id
      showForm: false, // 为了初始化空数据
    }
  },
  props: {
    templateId: {
      type: String | Number,
      default: '',
    },
  },
  components: {
    ConnectorModuleRuleForm
  },
  methods: {
    addRuleFormItem() {
      this.insertFieldOptionsList = [...this.insertFieldOptionsList, createConnectorRuleFormItem()];
    },
    onConnectorSelectRuleFormInputHandler(val) {
      // 添加子属性
      connectorFromFieldsAddChildren(this.fromFieldList);
      this.insertFieldOptionsList = val;
    },
    async openDialog(defaultForm) {
      this.showForm = false
      // 先清空
      this.selectTypeName = defaultForm.projectTaskName
      this.taskId = defaultForm.id
      // 先调ruleDetail为空 再调getCreateOptions
      await ProjectManage.taskRuleDetail({projectTypeId: this.templateId, id: defaultForm?.id}).then((res) => {
        if (!res.success) return this.$message.error(res.message)

        let { fromFieldList, toFieldList, insertFieldOptionsList } = res.data
        // 接口数据转换为连接器组件
      

        if (fromFieldList?.length && toFieldList?.length) {
          this.toFieldList = toFieldList.map((item) => {
            if (item.fieldType === 'planStartTime' || item.fieldType === 'planEndTime') {
              item.fieldType = 'datetime'
            } 
            return item
          })
          this.fromFieldList = fromFieldList
          this.insertFieldOptionsList = (insertFieldOptionsList || []).map((item) => {
            return ConnectorOptionsFieldOptionToConnectorRuleForm(item, toFieldList, false )
          })
          this.showForm = true
        } else {
          this.getConnectorDetail(defaultForm.taskFormId, defaultForm.taskType)
        }
      })
      this.isShow = true
      this.$nextTick(()=> {
        this.userNameStyleOverlapPolyfill()
      })
    },


     /**
     * @description 用户名样式重叠补丁
     */
     userNameStyleOverlapPolyfill() {
      
      const userInputList = (this.$el.querySelectorAll('.user-search input') || [])
      
      userInputList.forEach(userInputElement => {
        if (userInputElement.value) {
          userInputElement.value = ''
          userInputElement.placeholder = ''
        }
      })
      
    },
    getConnectorDetail(taskFormId, taskType) {
       const Types = {
         WORK_TASK: 'TASK',
         PAAS_TASK: 'PAAS',
       }

      // 新建规则
      let params = {
        fromBizTypeId: this.templateId,
        toBizTypeId:  taskFormId,
        fromBizType: 'PROJECT_MANAGER',
        toBizType: Types?.[taskType] ?? taskType,
      }
      // 先判断连接器数组是否是空
      getConnectorOptions(params).then((res) => {
        if (!res.success) return
        let { fromFieldList, toFieldList } = res.data
        if (fromFieldList?.length && toFieldList?.length) {
          this.fromFieldList = fromFieldList || []

          this.toFieldList = (toFieldList || []).map((item) => {
            if (item.fieldType === 'planStartTime' || item.fieldType === 'planEndTime') {
              item.fieldType = 'datetime'
            } 
            return item
          })

          if (this.toFieldList.length) {
            this.insertFieldOptionsList = this.toFieldList.filter(item=>{return item.required && item.supportInsert}).map(toField => {
              let formItem = createConnectorRuleFormItem(toField)
              return formItem
            })
          }
          this.showForm = true
        }
      })
    },

    queryPreTaskList() {
      ProjectManage.queryPreTaskList({projectTypeId: this.templateId}).then((res) => {
        if (!res.success) return this.$message.error(res.message)
        this.preTaskList = res.data || []
      })
    },
    cancel() {
      // 清空
      this.isShow = false
    },
    handleSelectType() {
      let parentType = this.$refs['cascaderType'].getCheckedNodes()?.[0]?.parent?.data?.type
      this.form.taskType = parentType
    },

    submitForm() {
      // 新建规则
      let conditionList = this.insertFieldOptionsList.map(item => {
          // 新建的话false 不然会影响到数据为数组和对象的处理
          return connectorRuleFormToConnectorOptionsFieldOption(item, false);
      })
      this.isShow = false
      this.$emit('submitRule', _.cloneDeep(conditionList), this.taskId)
    }
  }
}
</script>
<style lang="scss" scoped>

.task-form {
  .task-rule-wrap {
    margin: 20px 0;
      ::v-deep .form-item-project {
        height: 32px!important;
      }
  }
  
}
</style>